package model

import (
	"gorm.io/gorm"
	"sitego/pkg/database"
	"strings"
)

var name string
var pk string

// 指定AND查询条件
var wheres map[string]interface{}

// 指定RAW查询条件
var whereRaws string

// 字段截取
var fields string

// 排序
var orders string

// 指定OR查询条件
var whereOrs map[string]interface{}

// 是否查询加锁
var locks bool

// 错误信息
var error string

func SetTable(interface{}) {

}

func GetTable() {

}

func Wheres(where map[string]interface{}) map[string]interface{} {
	if len(where) > 0 {
		wheres = where
	}
	return wheres
}

func Fields(field string) string {
	if field != "" {
		fields = field
	}
	return fields
}

func Orders(order string) string {
	if order != "" {
		orders = order
	}
	return orders
}

func WhereOrs(whereOr []map[string]interface{}) []map[string]interface{} {
	return nil
}

func SetLooks(lock bool) {
	locks = lock
}

func GetLooks() bool {
	return locks
}

func GetField() {

}

func GetExists(model interface{}, where interface{}) bool {
	var count int64
	database.DB.Model(model).Where(where).Count(&count)
	return count > 0
}

func GetCount(model interface{}, where map[string]interface{}) int64 {
	var count int64
	database.DB.Model(model).Where(where).Count(&count)
	return count
}

func query(model interface{}, where map[string]interface{}, field string, order string) *gorm.DB {
	// 获取默认查询参数
	wheres := Wheres(where)
	fields := Fields(field)
	orders := Orders(order)

	// 如果传入的查询参数不为空，则使用传入的参数
	if len(where) > 0 {
		wheres = where
	}
	if field != "" {
		fields = field
	}
	if order != "" {
		orders = order
	}

	// 构建查询语句
	query := database.DB.Model(model)

	// 存在 where 查询
	if len(wheres) > 0 {
		// 主键查询
		if val, ok := wheres[pk]; ok && isNumeric(val) {
			query = query.Where("? = ?", pk, val)
		} else {
			query = query.Where(wheres)
		}
	}

	// 存在 whereOr 查询

	// 存在 order 排序
	if orders != "" {
		query = query.Order(orders)
	}

	// 指定字段查询
	if fields != "" {
		// 排除查询
		except := false
		if strings.HasPrefix(fields, "-") {
			except = true
			fields = strings.TrimPrefix(fields, "-")
		}
		if except {
			query = query.Select("*, -" + fields)
		} else {
			query = query.Select(fields)
		}
	}

	return query
}

func isNumeric(val interface{}) bool {
	switch val.(type) {
	case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
		return true
	default:
		return false
	}
}

func SetError(err string) bool {
	error = err
	return false
}

func GetError() string {
	return error
}
